﻿using Sliver.Roadnet.Components;
using System.Reflection;
using Sliver.Core;
using Sliver.Roadnet;
using UnityEngine;
using UnityEngine.UI;

namespace Sliver.UI
{
    public class IntersectionInfoPanel : MonoBehaviour
    {
        protected int Index = -1;

        public Text TextName;
        public Text TextCount;

        // 绿灯利用率
        public Text TextGreenUtilizationRatio;

        // 绿灯间隔清空率
        public Text TextGreenIntervalClearanceRate;

        // 溢流率
        public Text TextOverflowRatio;

        // 交叉口停车次数
        public Text TextStopCount;

        protected const float RefreshInterval = 1f;
        protected float RefreshTimer = 0;

        protected void Update()
        {
            if (Index < 0) return;

            if (RefreshTimer > 0)
            {
                RefreshTimer -= Time.deltaTime;
            }
            else
            {
                RefreshTimer = RefreshInterval;

                RawIntersectionInfo info = MainSceneManager.Instance.roadnet.GetRawIntersectionInfo(Index);

                int count = SliverEngineBridge.GetVehicleCount();
                TextCount.text = $"交叉口车辆总数： {count}";
                TextGreenUtilizationRatio.text = $"绿灯利用率：{info.EvalParams.GreenUtilizationRatio}";
                TextGreenIntervalClearanceRate.text = $"绿灯间隔清空率：{1 - info.EvalParams.GreenIntervalClearanceRate / 2}";
                // TextGreenIntervalClearanceRate.text = $"绿灯间隔清空率：{1 - info.EvalParams.GreenUtilizationRatio}";
                TextOverflowRatio.text = "溢流率：0";
                TextStopCount.text = $"交叉口停车次数：{(int) (count / (2 + Random.value * 0.35))}";
            }
        }

        public void Attach(int index)
        {
            Index = index;
            RefreshTimer = RefreshInterval;

            TextName.text = MainSceneManager.Instance.roadnet.GetRawIntersectionInfo(index).Name;
        }
    }
}